//
//  LGLungFollowPatientController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/7/9.
//  批量选择患者

#import "LGLungFollowPatientController.h"
#import "LGLungFollowPatientCell.h"
#import "LGPatientHomeHeaderView.h"
//筛选
#import "LGCommonScreenView.h"
#import "LGPatientSectionView.h"
@interface LGLungFollowPatientController ()<UITableViewDelegate,UITableViewDataSource,LGBottomButtonDelegate,LGPatientHeaderDelegate>
/**   */
@property (nonatomic , strong)LGPatientHomeHeaderView *headerView;
/**   */
@property (nonatomic , strong)LGBottomButtonView *bottomView;
/**   */
@property (nonatomic , strong)LGCommonScreenView *screenView;
/**   */
@property (nonatomic , strong)UITextField *searchTF;
/**   */
@property (nonatomic , strong)UIButton *searchBtn;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *selectArray;
/**  筛选条件 */
@property (nonatomic , strong)NSMutableDictionary *screenDic;
/**   */
@property (nonatomic , copy)NSString *pageNo;

@end

@implementation LGLungFollowPatientController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"批量选择患者";
    [self.view addSubview:self.searchTF];
    [self.view addSubview:self.searchBtn];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self emptyViewWithSuperView:self.tableView frame:CGRectMake(0, kMaxY(self.headerView.frame), Screen_W, self.tableView.bounds.size.height-self.headerView.bounds.size.height)];
    [[UIApplication sharedApplication].keyWindow addSubview:self.screenView];
    [self requestScreenData];
}

-(void)setPatientArray:(NSArray *)patientArray{
    _patientArray = patientArray;
    for (NSInteger i=0; i<patientArray.count; i++) {
        [self.selectArray addObject:LGNSString(patientArray[i])];
    }
    self.headerView.selectCount = [NSString stringWithFormat:@"%ld",self.selectArray.count];
}


//请求筛选数据
-(void)requestScreenData{
    [RequestUtil withPOST:@"/doctor/patient.patient/filter" parameters:@{@"is_team":@"1"} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.screenView.itemArray = returnData;
            [self sureScreenAction];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestData{
    self.pageNo = @"1";
    [self requestMoreData];
}

-(void)requestMoreData{
    NSMutableDictionary *parama = [NSMutableDictionary dictionary];
    [parama setValue:[ObjectTool objectToJson:self.screenDic] forKey:@"filter"];
    [parama setValue:@"1" forKey:@"is_team"];
    [parama setValue:self.pageNo forKey:@"pageNo"];
    [parama setValue:@"20" forKey:@"pageSize"];
    [RequestUtil withPOST:@"/doctor/patient.patient/search" parameters:parama withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if([self.pageNo isEqualToString:@"1"]){
            self.dataArray = [NSMutableArray array];
        }
        if(code == 200){
            NSArray *tempArray = returnData[@"data"];
            if(tempArray.count>0){
                self.pageNo = [NSString stringWithFormat:@"%ld",[returnData[@"current_page"] integerValue]+1];
                [self.dataArray addObjectsFromArray:tempArray];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无符合条件的患者" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无符合条件的患者" offset:0];
        }
    }];
}

//筛选
-(void)screenBtnAction{
    [self.screenView showScreenViewAnimation];
}

//重置筛选
-(void)resetScreenAction{
    self.screenDic = [NSMutableDictionary dictionary];
    [self.screenView resetDataAction];
    [self.screenView closeViewAction];
    self.headerView.dataDic = @{};
    [self requestData];
}

//删除筛查选项
-(void)deleteScreenItem:(NSDictionary *)itemDic{
    NSString *key = LGNSString(itemDic[@"key"]);
    NSString *content = LGNSString(itemDic[@"title"]);
    if([self.screenView.screenDic.allKeys containsObject:key]){
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:self.screenView.screenDic[key]];
        if([tempDic.allKeys containsObject:content]){
            [tempDic removeObjectForKey:content];
        }
        [self.screenView.screenDic setValue:tempDic forKey:key];
    }
    [self.screenView.collectionView reloadData];
    [self sureScreenAction];
}

//确定筛选
-(void)sureScreenAction{
    self.screenDic = [NSMutableDictionary dictionary];
    NSArray *keyArray = self.screenView.screenDic.allKeys;
    for (NSInteger i=0; i<keyArray.count; i++) {
        NSDictionary *tempDic = self.screenView.screenDic[keyArray[i]];
        NSArray *titleArray = tempDic.allKeys;
        if(titleArray.count>0){
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSInteger j=0; j<titleArray.count; j++) {
                [tempArray addObject:@{@"title":titleArray[j],@"ids":tempDic[titleArray[j]]}];
            }
            [self.screenDic setValue:tempArray forKey:keyArray[i]];
        }
    }
    self.headerView.dataDic = self.screenView.screenDic;
    [self.screenView closeViewAction];
    [self requestData];
}

//headView高度变化
-(void)headViewHeightChanged:(CGFloat)height{
    self.headerView.frame = CGRectMake(0, 0, Screen_W, height);
    self.tableView.tableHeaderView = self.headerView;
    self.emptyView.frame = CGRectMake(0, height, Screen_W, self.tableView.bounds.size.height-height);
}

-(void)searchPatients{
    [RequestUtil withPOST:@"/doctor/patient.patient/search" parameters:@{@"keyword":self.searchTF.text,@"pageSize":@"100"} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData[@"data"];
            [self.tableView reloadData];
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"没有找到内容" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"没有找到内容" offset:0];
        }
    }];
}

-(void)bottomButtonTouched{
    if (self.selectPatientSuccess) {
        self.selectPatientSuccess(self.selectArray);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)textFieldEditingChanged:(UITextField *)textField{
    [self searchPatients];
}

-(void)searchBtnAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        //开始搜索
        [self.searchTF becomeFirstResponder];
    }else{
        //结束搜索
        [self.searchTF resignFirstResponder];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *patiendid = LGNSString(self.dataArray[indexPath.row][@"patient_id"]);
    LGLungFollowPatientCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    cell.isSelected = [self.selectArray containsObject:patiendid]?YES:NO;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   __block NSString *patiendid = LGNSString(self.dataArray[indexPath.row][@"patient_id"]);
    [RequestUtil withPOST:@"/doctor/Careplan/checkedCaresend" parameters:@{@"patient_id":patiendid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            if ([self.selectArray containsObject:patiendid]) {
                [self.selectArray removeObject:patiendid];
            }else{
                [self.selectArray addObject:patiendid];
            }
            [self.tableView reloadData];
            self.headerView.selectCount = [NSString stringWithFormat:@"%ld",self.selectArray.count];

        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
    return footView;
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    CGFloat tableH = self.tableView.bounds.size.height;
    self.emptyView.frame = CGRectMake(0, kMaxY(self.headerView.frame), Screen_W, tableH-self.headerView.bounds.size.height);
}


#pragma mark
#pragma mark ====> 创建控件
-(NSMutableDictionary *)screenDic{
    if(!_screenDic){
        _screenDic = [NSMutableDictionary dictionary];
    }
    return _screenDic;
}

-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)selectArray{
    if(!_selectArray){
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

-(UITextField *)searchTF{
    if(!_searchTF){
        _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(12), viewPix(6), Screen_W-viewPix(72), viewPix(32))];
        _searchTF.tintColor = [UIColor colorWithString:@"#333333"];
        _searchTF.textColor = [UIColor colorWithString:@"#333333"];
        _searchTF.backgroundColor = [UIColor whiteColor];
        _searchTF.textAlignment = NSTextAlignmentLeft;
        _searchTF.keyboardType = UIKeyboardTypeDefault;
        _searchTF.placeholder = @"输入患者姓名/病案号进行查找";
        _searchTF.cornerRidus = viewPix(16);
        _searchTF.font = LGFont(15);
        _searchTF.leftViewMode = UITextFieldViewModeAlways;
        _searchTF.leftView = [self searchLeftView];
        [_searchTF addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTF;
}

-(UIButton *)searchBtn{
    if(!_searchBtn){
        _searchBtn = [UIButton buttonWithTitle:@"搜索" titleFont:LGFontWeight(14, UIFontWeightMedium) normalColor:kThemeColor selectColor:@"#999999"];
        _searchBtn.frame = CGRectMake(Screen_W-viewPix(60), viewPix(6), viewPix(60), viewPix(32));
        [_searchBtn setTitle:@"取消" forState:UIControlStateSelected];
        [_searchBtn addTarget:self action:@selector(searchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchBtn;
}
     
 -(LGPatientHomeHeaderView *)headerView{
     if(!_headerView){
         _headerView = [[LGPatientHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(44))];
         _headerView.groupBtn.hidden = YES;
         _headerView.delegate = self;
         [_headerView.screenBtn addTarget:self action:@selector(screenBtnAction) forControlEvents:UIControlEventTouchUpInside];
     }
     return _headerView;
 }

 -(LGCommonScreenView *)screenView{
     if(!_screenView){
         _screenView = [[LGCommonScreenView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
         [_screenView.resetBtn addTarget:self action:@selector(resetScreenAction) forControlEvents:UIControlEventTouchUpInside];
         [_screenView.sureBtn addTarget:self action:@selector(sureScreenAction) forControlEvents:UIControlEventTouchUpInside];
         _screenView.hidden = YES;
     }
     return _screenView;
 }

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewPix(44), Screen_W, Screen_H-topBarHeight-viewPix(44)-viewPix(65)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGLungFollowPatientCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headerView;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestScreenData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    }
    return _tableView;
}

-(LGBottomButtonView *)bottomView{
    if(!_bottomView){
        _bottomView = [[LGBottomButtonView alloc]initWithTitle:@"确定" color:kThemeColor type:LGBottomButtonTypeBack frame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(65)+bottomSafeBarHeight/4.0)];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

-(UIView *)searchLeftView{
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(35), viewPix(32))];
    UIImageView *iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"searchGray16"]];
    iconView.frame = CGRectMake(viewPix(10), viewPix(8), viewPix(16), viewPix(16));
    [baseView addSubview:iconView];
    return baseView;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
